<template>
  <div class="upload-wrap">
    <div v-if="isLook || attaches.length">
      <p v-if="attaches && attaches.length"
         :class="['span','span1']">
        <label>{{title}}</label>
      <ul class="flex img-wrap">
        <li v-for="(item,index) in attaches"
            :key="index"
            class="img-item">
          <img :src="item.url || item"
               alt=""
               class="img"
               @click="previewImage(item)" />
          <nr-img-preview v-if="preview"
                          :src="previewSrc"
                          :on-click="closeImgPreview"
                          :on-keydown="keydownCloseImgPreview" />
          <div class="file-name">{{item.name}}</div>
        </li>
      </ul>
      </p>
      <div v-if="!attaches || attaches.length === 0">{{`暂无${title}`}}</div>
    </div>
    <div class="upload-box">
      <el-upload v-if="!isLook"
                 v-bind="$attrs"
                 :http-request="uploadFile"
                 :action="ATactionUrl"
                 class="upload-ticket-imgs"
                 :headers="headers"
                 :class="{ 'hide-upload-btn': hideUploadBtn }"
                 list-type="picture-card"
                 :limit="limit"
                 :file-list="fileList"
                 :before-upload="beforeUpload"
                 :on-preview="handlePictureCardPreview"
                 :on-change="handleEditChange"
                 :on-exceed="handleExceed"
                 :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
        <!-- <div>文件名字</div> -->
        <div slot="file"
             slot-scope="{file}"
             class="img-style">
          <img class="el-upload-list__item-thumbnail"
               :src="file.url"
               alt="">
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span class="el-upload-list__item-delete"
                  @click="handleRemove(file,fileList)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
          <el-checkbox v-if="check"
                       v-model="file.check"
                       label=""
                       :true-label="1"
                       :false-label="0"
                       :title="imgTip"
                       @change="handleChecked(file)">
          </el-checkbox>
        </div>
        <div slot="tip"
             class="el-upload__tip">{{uploadPrompt}}</div>
      </el-upload>
    </div>
    <el-dialog :visible.sync="dialogVisible"
               title="图片"
               append-to-body>
      <img width="100%"
           class="imgsty"
           :src="dialogImageUrl"
           alt="">
    </el-dialog>
  </div>
</template>

<script>
import nrImgPreview from "@/components/nr/imgPreview/Index";

import { parsePicture, uploadPicture } from "@/api/modules/upload";
export default {
  name: "UploadIicense",
  components: { nrImgPreview },
  inheritAttrs: true,
  props: {
    // uploadAnalysisList: {
    //   type: Object,
    //   default: () => {
    //     return {
    //       uploadLicense: '/user/photoRecognized/businessLicense',
    //       uploadPicture: '/proxy/oss/open/uploadFile'
    //     }
    //   }
    // },
    check: {
      type: Boolean,
      default: false,
    },
    // 上传个数
    limit: {
      type: Number,
      default: 1,
    },
    imgTip: {
      type: String,
      default: "",
    },
    // 是否解析图片
    isPicture: {
      type: Boolean,
      default: false,
    },
    // 上传类型限制
    type: {
      type: String,
      default: "",
    },
    isLook: {
      // 是否是查看
      type: Boolean,
      default: false,
      required: false,
    },
    // 回显照片
    attaches: {
      type: Array,
      default: () => [],
    },
    // title
    title: {
      type: String,
      default: '图片',
    },
    isDisabled: {
      type: Boolean,
      default: false,
    },
  },
  data () {
    return {
      preview: false,
      checkedImg: [],
      imgList: [],
      fileList: [],
      parseData: {},
      ATactionUrl: "",
      isUploadShow: false,
      hideUploadBtn: null,
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("token"),
      },
      dialogImageUrl: "",
      dialogVisible: false,
      uploadPrompt:
        this.type === "file"
          ? "上传文件只能是 pdf、doc、docx、xls、xlsx格式!/不能超过 2MB!"
          : "上传图片只能是 JPG、JPEG、gif、bmp、PNG 格式!/不能超过 2MB!",
      pic: null,
      file: null,
      previewSrc: "",
      limitFix: null,
    };
  },
  watch: {
    // attaches: {
    //   handler (val) {
    //     console.log('val-----------?', val)
    //   }
    // }
  },
  mounted () {
    let appletsLen = this.attaches.length + 1;
    this.limitFix = this.limit - appletsLen;
  },
  methods: {
    previewImage (item) {
      this.preview = true;
      this.previewSrc = item.url || item;
    },
    closeImgPreview () {
      this.preview = false;
    },
    // submitUpload () {
    //   this.$refs.upload.submit();
    // },
    handleChecked (val) {
      let file = this.fileList.filter((item) => {
        return item.check;
      });
      const files = file.map((x) => {
        return {
          name: x.fileName,
          url: x.url,
          type: 1,
        };
      });
      this.$emit("syncImg", files);
    },
    handleRemove (file, fileList) {
      this.hideUploadBtn = fileList.length >= this.limit;
      // this.fileList = fileList;
      this.fileList = fileList.filter((sub) => sub.fileUrl !== file.fileUrl);
      console.log('fileList???????', this.fileList)
      // this.$emit('uploadSuccess', this.fileList)
      // this.display = fileList.length >= this.limit
    },
    handleEditChange (file, fileList) {
      this.hideUploadBtn = fileList.length >= this.limit;
      // this.fileList = fileList
      // this.display = fileList.length >= this.limit
    },
    handlePreview (file) {
      console.log(file);
    },
    handleExceed () {
      // if (this.attaches.length > 0) {
      //   /* 小程序扫码图片存在时 上传张数需包括小程序扫码的图片 */
      //   let appletsLen = this.attaches.length + 1
      //   this.limitFix = this.limit - appletsLen
      //   console.log('appletsLenappletsLen', appletsLen)
      //   console.log('limitlimitlimitlimit', this.limit)
      // }
      return this.$message(
        `最多可上传${this.limit}个${this.type === "file" ? "文件" : "照片"}`
      );
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传文件限制
    beforeUpload (file) {
      if (this.type === "file") {
        return this.fileDoc(file);
      } else if (this.type === "png") {
        return this.picture(file);
      } else {
        this.fileDoc(file);
        this.picture(file);
      }
    },
    uploadFile (file) {
      let form = new FormData();
      // 文件属性
      form.append("file", file.file);
      this.upload(form);
      // this.parsePictureCall(form)
    },

    upload (formData) {
      // 上传图片统一接口
      let p1 = new Promise((resolve, reject) => {
        uploadPicture(formData).then((response) => {
          let { data } = response;
          resolve(data);
          this.fileList = [...this.fileList, { url: data[0] }];
        });
      });
      let resList = [p1];
      //  解析图片
      if (this.isPicture) {
        let p2 = new Promise((resolve, reject) => {
          parsePicture(formData).then((response) => {
            let { code, message, data } = response;
            if (code === 0) {
              if (this.isPicture) {
                resolve(data);
                this.$message.success(message);
              } else {
                return;
              }
            } else {
              resolve({});
              if (this.isPicture) return this.$message.warning(message);
            }
          });
        });
        resList.push(p2);
      }
      Promise.all(resList)
        .then((result) => {
          if (this.isPicture) {
            let data = Object.assign(result[1], { fileUrl: result[0][0] });
            this.$emit("uploadSuccess", data);
          } else {
            this.$emit("uploadSuccess", this.fileList);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 上传图片限制
    picture (file) {
      let types = [
        "image/jpeg",
        "image/jpg",
        "image/gif",
        "image/bmp",
        "image/png",
      ];
      const isImage = types.includes(file.type);
      const isLtSize = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error("上传图片只能是 JPG、JPEG、gif、bmp、PNG 格式!");
        return false;
      }
      if (!isLtSize) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
    // 上传文件限制
    fileDoc (file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteListFile = ["pdf", "doc", "docx", "xls", "xlsx"];
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (whiteListFile.indexOf(fileSuffix) === -1) {
        this.$message.error("上传文件只能是 pdf、doc、docx、xls、xlsx格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
        return false;
      }
    },
    keydownCloseImgPreview (e) {
      if (e && e.keyCode == 27) {
        this.preview = false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.upload-box {
  position: relative;
}
.upload-ticket-imgs {
  position: relative;
  padding-bottom: 5px;
  .upload-wrap {
    display: flex;
    align-items: center;
  }
  &.hide-upload-btn {
    /deep/.el-upload--picture-card {
      display: none;
    }
  }
  .el-upload-list__item-thumbnail {
    height: 100px;
  }
  .img-style {
    position: relative;
  }

  .el-checkbox {
    position: absolute;
    top: 0;
    left: 0;
    line-height: 20px;
  }
}
.upload-ticket-imgs /deep/ .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.upload-ticket-imgs /deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.file-name {
  width: 100px;
  white-space: pre-wrap;
  word-break: break-all;
}
.span {
  box-sizing: border-box;
  font-size: 14px;
  label {
    display: inline-block;
    margin-right: 10px;
    // min-width: 28%;
    font-size: 14px;
  }
  span {
    font-weight: bold;
  }
  .img-wrap {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    list-style: none;
  }
  .img-item {
    margin-right: 20px;
    .img {
      width: 100px;
      height: 100px;
      background-color: var(--prev-border-color-grey);
      cursor: pointer;
      border: 1px solid var(--prev-border-color-grey);
    }
    p {
      text-align: center;
    }
  }
}
.span1 {
  width: 100%;
  display: grid;
}
.span2 {
  width: 50%;
}
.span4 {
  width: 25%;
}
.imgsty {
  height: 75vh !important;
}
/deep/ .el-dialog {
  margin-top: 10vh !important;
}
/deep/ .el-dialog__body {
  padding: 0 20px 20px 20px;
}
</style>
